package com.xieyong.mywebsite.controller;

import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.model.dto.Result;
import com.xieyong.mywebsite.model.entity.Category;
import com.xieyong.mywebsite.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result<Category> add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @PutMapping
    public Result<Category> update(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.update(category);
        return Result.success();
    }

    @DeleteMapping
    public Result<Category> delete(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.delete(category);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Category> deleteById(@PathVariable Integer id) {
        categoryService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/page")
    public Result<PageInfo<Category>> getPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Category category) {
        PageInfo<Category> page = categoryService.page(pageNum,pageSize,category);
        return Result.success(page);
    }

    @GetMapping()
    public Result<List<Category>> list() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }

    @GetMapping("/detail")
    public Result<Category> detail(@RequestParam Integer id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }
}
